﻿using AutoMapper;
using B.S.BaseData.Api.Write.Applicantion.Command.HospitalCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.AI;
using MediatR;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.HospitalCommandHandler
{
    public class PatientAddCommandHandler : IRequestHandler<PatientAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<PatientModel> _repository;
        private readonly IBaseRepository<IdentityModel> _identityRepository;
        private readonly IBaseRepository<HealthCareModel> _healthCareRepository;
        private readonly IMapper _mapper;
        public PatientAddCommandHandler(IBaseRepository<PatientModel> repository, IMapper mapper, IBaseRepository<IdentityModel> identityRepository, IBaseRepository<HealthCareModel> healthCareRepository)
        {
            _repository = repository;
            _mapper = mapper;
            _identityRepository = identityRepository;
            _healthCareRepository = healthCareRepository;
        }
        public async Task<APIResult<int>> Handle(PatientAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            var res =await _identityRepository.GetValues(x=>x.PatientIdentityCard == request.PatientIdentityCard);
            if (res == null)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "先输入正确的身份证号码";
                return await Task.FromResult(result);
            }
            var data = await _repository.GetValues(x => x.PatientIdentityCard == request.PatientIdentityCard);
            if (data != null)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "该实名身份已被注册";
                return await Task.FromResult(result);
            }

            var res1 = await _healthCareRepository.GetValues(x => x.HealthCareCard == request.HealthCareCard);
            if (res1 == null)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "先输入正确的医保卡";
                return await Task.FromResult(result);
            }

            var list= _mapper.Map<PatientModel>(request);
            result.Code = ApiEnum.Fail;
            result.Msg = "患者信息添加成功";
            result.Data =await _repository.CreateAsync(list);
            return await Task.FromResult(result);
        }
    }
}
